// 持久化存储类型（可选 'local' 或 'session'）
type StorageType = 'local' | 'session'

export const setStorage = <T>(key: string, value: T, type: StorageType = 'local'): void => {
  if (typeof window === 'undefined') return // SSR环境不执行

  try {
    const storage = type === 'local' ? localStorage : sessionStorage
    storage.setItem(key, JSON.stringify(value))
  } catch (error) {
    console.error('存储数据失败:', error)
  }
}

export const getStorage = <T>(
  key: string,
  defaultValue?: T,
  type: StorageType = 'local'
): T | undefined => {
  if (typeof window === 'undefined') return defaultValue // SSR环境返回默认值

  try {
    const storage = type === 'local' ? localStorage : sessionStorage
    const storedValue = storage.getItem(key)
    return storedValue ? (JSON.parse(storedValue) as T) : defaultValue
  } catch (error) {
    console.error('读取存储数据失败:', error)
    return defaultValue
  }
}
